package com.ugoodtech.mdcc.web.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.dto.StationResponse;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.CoreStationService;
import com.ugoodtech.mdcc.core.utils.ArrayStringUtil;
import com.ugoodtech.mdcc.core.utils.DateUtil;
import com.ugoodtech.mdcc.core.utils.ValidateUtil;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.service.StationTechColorReportService;
import com.ugoodtech.mdcc.core.utils.AnswerOtherUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

@Api(description = "技术颜色报告相关接口")
@RestController
@RequestMapping("colorReport")
public class CreateStationColorReport extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CreateStationColorReport.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationTechColorReportService stationTechColorReportService;

    @Autowired
    private NationRepository nationRepository;

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private AuditColorReportRepository auditColorReportRepository;

    @Autowired
    private AuditReportRepository auditReportRepository;

    @Autowired
    private UserLogRepository userLogRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CoreStationService coreStationService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);


    @ApiOperation("颜色报告审核通过--改")
    @RequestMapping(value = "auditTrue", method = RequestMethod.POST)
    public JsonResponse auditTrue(@ApiParam("报告编号") @RequestParam(value = "reportId") Long reportId,
                                  @ApiParam("操作者ID") @RequestParam(value = "loginUserId", required = false) Long userId
    ) {
//        if (reportId == null || reportId == 0) {
//            return JsonResponse.errorResponseWithError("抱歉", "参数错误");
//        }
//        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.COLOR_REPORT_AUDIT);
//        boolean b = clientUser.getRole().getAuthorities().contains(m);
//        if (b == false) {
//            return JsonResponse.errorResponseWithError("抱歉", "您没有此权限:维修站技术颜色能力分析报告审核");
//        }
        isUserLogin();
        User user = userRepository.findOne(userId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登录用户");
        }
        AuditReport auditReport = auditReportRepository.findOne(reportId);
        if (auditReport.getStation() != null) {
            JsonResponse jsonResponse = toComplete(user, auditReport, Constants.REPORT_COMPLETE, reportId, auditReport.getStation().getId(), true);
            if (!jsonResponse.isSuccess()) {
                return jsonResponse;
            }
        } else {
            JsonResponse jsonResponse = toComplete(user, auditReport, Constants.REPORT_COMPLETE, reportId, null, true);
            if (!jsonResponse.isSuccess()) {
                return jsonResponse;
            }
        }
        JsonResponse jsonResponse = stationTechColorReportService.auditTrue(user, reportId,auditReport.getUserType());
//        if (jsonResponse.isSuccess()) {
//            UserLog userLog = userLogService.addUserLog(user, null, reportId, Constants.CUSTOMER_REPORT, LogConstants.operate_type_confirm, LogConstants.business_type_color_report, null, null);
//            userLogService.setLogStation(userLog);
//        }
        return jsonResponse;
    }

    private JsonResponse toComplete(User user, AuditReport auditReport, String reportType,
                                    Long reCreateRepirtId, Long stationId, Boolean auditTrue) {
        //判断是否是提交--提交  反复提交
        if (reCreateRepirtId != null && reCreateRepirtId != 0) {
            AuditColorReport report;
            //设置是否有其他品牌
            report = auditColorReportRepository.selectAuditReport(auditReport.getId(),175L);
            if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                auditReport.setOtherBrnad(true);
            } else {
                auditReport.setOtherBrnad(false);
            }
            auditReportRepository.save(auditReport);

            auditReport.setAuditing(Constants.AUDIT_APPLY);
            if (auditReport.getStation() != null) {
                auditReport.setReAudit(true);
                logger.info("重复提交：更新题目");
            } else {
                auditReport.setReAudit(false);
                logger.info("审核-提交：更新题目");
            }
            Date date = new Date();
            auditReport.setUpdateTime(date);
            auditReport.setUpdateTimeStr(dateToStr(date));
            auditReport.setSupplement(false);
            auditReportRepository.save(auditReport);
            logger.info("<<<<<<<<<<<<<<<<<<更新完毕>>>>>>>>>>>>>>>>>");
            logger.info("***************************************************************");
            return JsonResponse.successResponse();
        }
        return JsonResponse.errorResponseWithError("抱歉", "审核失败");
    }

    //将日期转换成字符串
    private String dateToStr(Date date) {
        return simpleDateFormat.format(date);
    }

    @ApiOperation("颜色报告审核不通过--改")
    @RequestMapping(value = "auditFalse", method = RequestMethod.POST)
    public JsonResponse auditFalse(@ApiParam("操作者ID") @RequestParam(value = "loginUserId", required = false) Long userId,
                                   @ApiParam("报告编号") @RequestParam(value = "reportId") Long reportId,
                                   @ApiParam("审核不通过原因") @RequestParam(value = "auditNote") String auditNote
    ) {
        isUserLogin();
        User user = userRepository.findOne(userId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登录用户");
        }
        if (reportId == null || reportId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "报告ID参数不对");
        }
        if (StringUtils.isEmpty(auditNote)) {
            return JsonResponse.errorResponseWithError("抱歉", "不通过原因不能为空");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("str", auditNote);
        UserLog userLog = userLogService.addUserLog(user, null, reportId, Constants.CUSTOMER_REPORT, LogConstants.operate_type_not_confirm, LogConstants.business_type_color_report, null, data);
        userLogService.setLogStation(userLog);
        JsonResponse jsonResponse = stationTechColorReportService.auditFalse(user, reportId, auditNote);
        if (!jsonResponse.isSuccess()) {
            userLog.setDeleted(true);
            userLogRepository.save(userLog);
        }
        return jsonResponse;
    }

    @ApiOperation("编辑待审核的基础报告")
    @RequestMapping(value = "/editColorReport_Audit", method = RequestMethod.POST)
    public JsonResponse editColorReport_Audit(@ApiParam("操作者ID") @RequestParam(value = "loginUserId", required = false) Long loginUserId,
                                              @ApiParam("报告编号") @RequestParam(value = "reportId") Long reportId,
                                              @ApiParam("问题ID") @RequestParam(value = "questionId") Long questionId,
                                              @ApiParam("答案ID") @RequestParam(value = "answerId", required = false) String answerId,
                                              @ApiParam("文本答案") @RequestParam(value = "answerOther", required = false) String answer_other,
                                              @ApiParam("省份") @RequestParam(value = "province", required = false) String province,
                                              @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                              @ApiParam("照片") @RequestParam(value = "answerPhoto", required = false) String answerPhoto) {
        isUserLogin();
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登录用户");
        }
//        if (questionId == 4) {
//            User toUser = userRepository.findByUsername(answer_other);
//            if (toUser != null) {
//                return JsonResponse.errorResponseWithError("抱歉", "该手机号已经被注册");
//            }
//        }
        //判断品牌是否包含其他品牌
        if (questionId == 8) {
            AuditReport auditReport = auditReportRepository.findOne(reportId);
            if (null != auditReport) {
                if (StringUtils.isNotEmpty(answer_other)) {
                    auditReport.setOtherBrnad(true);
                } else {
                    auditReport.setOtherBrnad(false);
                }
                auditReportRepository.save(auditReport);
            }
        }
        Question question = questionRepository.findOne(questionId);
        AuditColorReport stationColorReport = auditColorReportRepository.selectReport(reportId, questionId);
        String originAnswerId = stationColorReport.getAnswerId();
        String originAnswerOther = stationColorReport.getAnswerOther();
        if (stationColorReport == null && questionId == 186L) {
            AuditReport auditReport = auditReportRepository.findOne(reportId);
            stationColorReport.setAuditReport(auditReport);
            stationColorReport.setAnswerOther(answer_other);
            stationColorReport.setQuestionId(questionId);
            auditColorReportRepository.save(stationColorReport);
            return JsonResponse.successResponse();
        }
        if (stationColorReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到这道题");
        }
        if (StringUtils.isNotEmpty(answerPhoto)) {
            stationColorReport.setAnswerPhoto(answerPhoto);
        }
        if (StringUtils.isNotEmpty(answerId)) {
            stationColorReport.setAnswerId(answerId);
        }
        if (StringUtils.isNotEmpty(answer_other)) {
            stationColorReport.setAnswerOther(answer_other);
        }
        if (StringUtils.isNotEmpty(province)) {
            AuditColorReport colorReport = auditColorReportRepository.selectReport(reportId, 173L);
            colorReport.setAnswerOther(province);
            auditColorReportRepository.save(colorReport);
            return JsonResponse.successResponse();
        }
        if (StringUtils.isNotEmpty(city)) {
            AuditColorReport colorReport = auditColorReportRepository.selectReport(reportId, 174L);
            colorReport.setAnswerOther(city);
            auditColorReportRepository.save(colorReport);
            return JsonResponse.successResponse();
        }
        auditColorReportRepository.save(stationColorReport);
        AuditReport auditReport = stationColorReport.getAuditReport();
        Date date = new Date();
        auditReport.setUpdateTime(date);
        auditReport.setUpdateTimeStr(simpleDateFormat.format(date));
        auditReportRepository.save(auditReport);
        String desc = "";
        if (!originAnswerOther.equals(stationColorReport.getAnswerOther()) ||
                !filterAnswerId(originAnswerId).equals(stationColorReport.getAnswerId())) {
            desc += question.getSubject() + ":";
            desc += getAnswerString(originAnswerId) + AnswerOtherUtil.getOtherString(originAnswerOther) + "-->>" + getAnswerString(stationColorReport.getAnswerId()) + AnswerOtherUtil.getOtherString(stationColorReport.getAnswerOther()) + ",";
        }
        Map<String, Object> data = new HashMap<>();
        data.put("str", desc);
        UserLog userLog = userLogService.addUserLog(user, null, auditReport.getId(), Constants.CUSTOMER_REPORT, LogConstants.operate_type_edit, LogConstants.business_type_audit_report, null, data);
        userLogService.setLogStation(userLog);
        return JsonResponse.successResponse();
    }


    @ApiOperation("编辑基础报告")
    @RequestMapping(value = "/editColorReport", method = RequestMethod.POST)
    public JsonResponse editColorReport(@ApiParam("操作者ID") @RequestParam(value = "loginUserId", required = false) Long loginUserId,
                                        @ApiParam("报告编号") @RequestParam(value = "reportId") Long reportId,
                                        @ApiParam("问题ID") @RequestParam(value = "questionId") Long questionId,
                                        @ApiParam("答案ID") @RequestParam(value = "answerId", required = false) String answerId,
                                        @ApiParam("文本答案") @RequestParam(value = "answerOther", required = false) String answer_other,
                                        @ApiParam("省份") @RequestParam(value = "province", required = false) String province,
                                        @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                        @ApiParam("提交者身份") @RequestParam(value = "userType", required = false) Integer userType,
                                        @ApiParam("照片") @RequestParam(value = "answerPhoto", required = false) String answerPhoto) {
        isUserLogin();
        User loginUser = userRepository.findOne(loginUserId);
        if (loginUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登录用户");
        }
        StationColorReport stationColorReport = stationColorReportRepository.selectReport(reportId, questionId);
        if (stationColorReport == null) {
            StationReport stationReport = stationReportRepository.findOne(reportId);
            stationColorReport = new StationColorReport();
            stationColorReport.setAnswerPhoto(answerPhoto);
            stationColorReport.setStationReport(stationReport);
            stationColorReport.setAnswerOther(answer_other);
            stationColorReport.setAnswerId(answerId);
            stationColorReport.setQuestionId(questionId);
            stationColorReportRepository.save(stationColorReport);


            Question question = questionRepository.findOne(questionId);
//            之前没有数据的时候比如没有填过地址=============也要记录日志=================================

            String desc = question.getSubject() + ":";
            desc += "-->>" + getAnswerString(answerId) + stationColorReport.getAnswerOther() + ",";
            Map<String, Object> data = new HashMap<>();
            data.put("str", desc);
            Station station = stationColorReport.getStationReport().getStation();
            userLogService.addUserLog(loginUser, station.getStationNum(), reportId, Constants.STATION_REPORT, LogConstants.operate_type_edit, LogConstants.business_type_station_info, null, data);
            return JsonResponse.successResponse();
        }
        String oldAnswer = stationColorReport.getAnswerId();
        String oldAnswerOther = stationColorReport.getAnswerOther();

        Station station = stationColorReport.getStationReport().getStation();
        if (StringUtils.isNotEmpty(answerId)) {
            stationColorReport.setAnswerId(answerId);
        }
        if (StringUtils.isNotEmpty(answer_other)) {
            stationColorReport.setAnswerOther(answer_other);
        } else {
            stationColorReport.setAnswerOther("");
        }
        if (StringUtils.isNotEmpty(answerPhoto)) {
            stationColorReport.setAnswerPhoto(answerPhoto);
        } else {
            stationColorReport.setAnswerPhoto("");
        }
        if (StringUtils.isNotEmpty(province)) {
            StationColorReport colorReport = stationColorReportRepository.selectReport(reportId, 173L);
            colorReport.setAnswerOther(province);
            station.setProvince(province);
            stationRepository.save(station);
            stationColorReportRepository.save(colorReport);
            return JsonResponse.successResponse();
        }
        if (StringUtils.isNotEmpty(city)) {
            StationColorReport colorReport = stationColorReportRepository.selectReport(reportId, 174L);
            colorReport.setAnswerOther(city);
            station.setCity(city);
            stationRepository.save(station);
            stationColorReportRepository.save(colorReport);
            return JsonResponse.successResponse();
        }
        if (questionId == 175) {
            List<Station> stationList = stationRepository.findByStationNameList(answer_other);
            if (!stationList.isEmpty()) {
                List<Station> unCheckOutStationId = coreStationService.getUnCheckoutStation(stationList);
                if (unCheckOutStationId.isEmpty()) {
                    return JsonResponse.errorResponseWithError("抱歉", "维修站名称重复了，已被其他审核通过的维修站使用！");
                }
                for (Station s : unCheckOutStationId) {
                    s.setDeleted(true);
                    s.setEnabled(false);
                    s.setName(s.getName() + "_deleted");
                    s.setStationNum(s.getStationNum() + "_deleted");
                    s.setUpdateTime(new Date());
                    stationRepository.save(s);
                }
            }
            station.setName(answer_other);
            stationRepository.save(station);
        }
        if (questionId == 181) {
            List<Station> stationList = stationRepository.findByStationNumList(answer_other);
            if (!stationList.isEmpty()) {
                List<Station> unCheckOutStationId = coreStationService.getUnCheckoutStation(stationList);
                if (unCheckOutStationId.isEmpty()) {
                    return JsonResponse.errorResponseWithError("抱歉", "维修站编号重复了，已被其他审核通过的维修站使用！");
                }
                for (Station s : unCheckOutStationId) {
                    s.setDeleted(true);
                    s.setEnabled(false);
                    s.setName(s.getName() + "_deleted");
                    s.setStationNum(s.getStationNum() + "_deleted");
                    s.setUpdateTime(new Date());
                    stationRepository.save(s);
                }
            }
            station.setStationNum(answer_other);
            stationRepository.save(station);
        }
        if (questionId == 2) {
            station.setContact(answer_other);
            stationRepository.save(station);
            UserProfile userProfile = userProfileRepository.findByUserId(station.getUser().getId());
            userProfile.setRealName(answer_other);
            userProfileRepository.save(userProfile);
        }
        if (questionId == 3) {
            UserProfile userProfile = userProfileRepository.findByUserId(station.getUser().getId());
            userProfile.setPosition(answer_other);
            userProfileRepository.save(userProfile);
        }
        if (questionId == 7) {
            if (StringUtils.isNotEmpty(answerId)) {
                QuestionAnswerOption answer = questionAnswerOptionRepository.findOne(Long.valueOf(answerId));
                if (answer == null) {
                    station.setCategory("");
                } else {
                    station.setCategory(answer.getName());
                    stationRepository.save(station);
                }
            }
        }
        if (questionId == 8) {
            if (StringUtils.isNotEmpty(answerId)) {
                String[] brandIds = answerId.split(",");
                StringBuffer brandBuffer = new StringBuffer("");
                for (String id : brandIds) {
                    QuestionAnswerOption answer = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (answer != null && answer.getName()!=null) {
                        if (id.equals("369")) {
                            station.setOtherBrand(true);
                            brandBuffer.append(answer_other + ",");
                        } else {
                            station.setOtherBrand(false);
                            brandBuffer.append(answer.getName() + ",");
                        }
                    }
                }
                station.setBrand(brandBuffer.toString());
            }
            stationRepository.save(station);
        }
        if (questionId == 4) {
            User toUser = userRepository.findByUsername(answer_other);

            if (toUser == null) {
                toUser = new User();
                UserProfile userProfile = new UserProfile();
                toUser.setUsername(answer_other);
                toUser.setUserType(UserType.customer);
                toUser.setPassword(passwordEncoder.encode(Constants.INIT_PASSWORD));
                toUser.setStationId(station.getId());
                userRepository.save(toUser);
                logger.info("查询联系人姓名");
                StationColorReport colorReport = stationColorReportRepository.selectReport(reportId, 2L);
                station.setContact(colorReport.getAnswerOther());
                userProfile.setRealName(colorReport.getAnswerOther());

                logger.info("查询联系人职位");
                colorReport = stationColorReportRepository.selectReport(reportId, 3L);
                userProfile.setPosition(colorReport.getAnswerOther());
                userProfile.setTelephone(answer_other);
                userProfileRepository.save(userProfile);
//                if (toUser != null && toUser.getId().equals(user.getId())) {
//                    return JsonResponse.errorResponseWithError("抱歉", "该手机号已经被注册");
//                }
            }
            if (toUser.getUserType().equals(UserType.insiders)){
                return JsonResponse.errorResponseWithError("抱歉", "该人员是内部人员无法作为维修站联系人");
            }
            station.setUser(toUser);
        }
        stationColorReportRepository.save(stationColorReport);
        StationReport stationReport = stationColorReport.getStationReport();
        Date date = new Date();
        stationReport.setUpdateTime(date);
        stationReport.setUpdateTimeStr(simpleDateFormat.format(date));
        stationReport.setUserType(userType);
        stationReportRepository.save(stationReport);
        Question question = questionRepository.findOne(questionId);
        if (!filterAnswerOther(oldAnswerOther).equals(filterAnswerOther(stationColorReport.getAnswerOther())) ||
                (null != answerId && !filterAnswerId(oldAnswer).equals(answerId))) {
            String desc = question.getSubject() + ":";
            desc += getAnswerString(oldAnswer) + AnswerOtherUtil.getOtherString(oldAnswerOther) + "-->>" + getAnswerString(answerId) + stationColorReport.getAnswerOther() + ",";
            Map<String, Object> data = new HashMap<>();
            data.put("str", desc);
            userLogService.addUserLog(loginUser, station.getStationNum(), reportId, Constants.STATION_REPORT, LogConstants.operate_type_edit, LogConstants.business_type_station_info, null, data);
        }
        return JsonResponse.successResponse();
    }

    String getAnswerString(String answerIds) {
        List<String> answers = new ArrayList<>();
        List<Long> answerIdArray = ArrayStringUtil.getStringIds(answerIds);
        for (Long answerId : answerIdArray) {
            QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(answerId);
            answers.add(questionAnswerOption.getName());
        }
        return StringUtils.join(answers, ",");
    }

    String filterAnswerId(String answerIds) {
        if (null == answerIds) {
            return "";
        } else {
            return answerIds;
        }
    }

    String filterAnswerOther(String answerOther) {
        try {
            Long currentMin = Long.parseLong(answerOther);
            if (currentMin > 1000000) {
                Date date = new Date(currentMin);
                if (!ValidateUtil.isValidMobileNo(answerOther)) {
                    return DateUtil.formatDate(date, Constants.DATE_FORMAT);
                } else {
                    return answerOther;
                }
            } else {
                return answerOther;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return answerOther;
        }
    }

    private List<Long> idList = new ArrayList<>();


    @ApiOperation("获取基础报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/getColorReport", method = RequestMethod.GET)
    public JsonResponse getColorReport_Audit(Pageable pageable,
                                             @ApiParam("审核状态:{0:未通过，1:通过，2:未审核}") @RequestParam(value = "auditType", required = false) String auditType,
                                             @ApiParam("城市") @RequestParam(value = "provinces", required = false) String province,
                                             @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                             @ApiParam("站点类型") @RequestParam(value = "category", required = false) String category,
                                             @ApiParam("品牌") @RequestParam(value = "brandname", required = false) String brand,
                                             @ApiParam("维修站关键字") @RequestParam(value = "stationName", required = false) String stationName,
                                             @ApiParam("用户名字关键字") @RequestParam(value = "userName", required = false) String userName,
                                             @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum) {
        isUserLogin();
        idList = new ArrayList<>();
        QAuditReport qAuditReport = QAuditReport.auditReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qAuditReport.deleted.eq(false));
        builder.and(qAuditReport.enabled.eq(true));
        builder.and(qAuditReport.supplement.eq(false));
        builder.and(qAuditReport.auditing.eq(auditType));
        if (StringUtils.isNotEmpty(stationNum)) {
            getOtherBuliderIds(181L, stationNum, auditType, idList);
        }
        logger.info("判断维修站编号之后长度为:" + idList.size());
        if (StringUtils.isNotEmpty(province)) {
            getOtherBuliderIds(173L, province, auditType, idList);
        }
        logger.info("判断省份之后长度为:" + idList.size());
        if (StringUtils.isNotEmpty(city)) {
            getOtherBuliderIds(174L, city, auditType, idList);
        }
        logger.info("判断城市之后长度为:" + idList.size());
        if (StringUtils.isNotEmpty(category)) {
            QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.find_ByName(category);
            getOtherBuliderById(7L, questionAnswerOption.getId(), auditType, idList);
        }
        logger.info("判断维修站类型之后长度为:" + idList.size());
        if (StringUtils.isNotEmpty(brand)) {
            String[] brandArray = brand.split(",");
            for (String brandName : brandArray) {
                QuestionAnswerOption answerOption = questionAnswerOptionRepository.findByName(brandName);
                getOtherBuliderIds(8L, answerOption.getId().toString(), auditType, idList);
            }
        }
        logger.info("判断品牌之后长度为:" + idList.size());
        if (StringUtils.isNotEmpty(stationName)) {
            getOtherBuliderIds(175L, stationName, auditType, idList);
        }
        logger.info("判断维修站名称之后长度为:" + idList.size());
        List<Long> ids = new ArrayList<>();
        if (StringUtils.isNotEmpty(userName)) {
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
            if (userProfileList.size() > 0) {
                for (UserProfile userProfile : userProfileList) {
                    ids.add(userProfile.getUser().getId());
                }
            }
            builder.and(qAuditReport.user.id.in(ids));
        }
        HashSet h = new HashSet(idList);
        idList.clear();
        idList.addAll(h);
        if (idList != null && idList.size() > 0) {
            builder.and(qAuditReport.id.in(idList));
        }
        logger.info("去重之后长度为:" + idList.size());
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<AuditReport> colorReportList = auditReportRepository.findAll(builder, pageable);
        logger.info("查询之后数据有:" + colorReportList.getContent().size());
        List<StationResponse> stationResponseList = toStationResponse(colorReportList.getContent());
        logger.info("封装之后数据有:" + colorReportList.getContent().size());
        Page<StationResponse> stationResponsePage = new PageImpl(stationResponseList, pageable, colorReportList.getTotalElements());
        logger.info("设置返回值之后数据有:" + colorReportList.getContent().size());
        return JsonResponse.successResponseWithPageData(stationResponsePage);
    }


    public void getOtherBuliderIds(Long questionId, String str, String type, List<Long> idList) {
        QAuditColorReport qStationColorReport = QAuditColorReport.auditColorReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationColorReport.auditReport.auditing.eq(type));
        builder.and(qStationColorReport.questionId.eq(questionId));
        builder.and(qStationColorReport.answerOther.like("%" + str + "%"));
        List<AuditColorReport> auditColorReportList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);
        for (AuditColorReport auditColorReport : auditColorReportList) {
            idList.add(auditColorReport.getAuditReport().getId());
        }
    }

    public void getOtherBuliderById(Long questionId, Long id, String type, List<Long> idList) {
        QAuditColorReport qStationColorReport = QAuditColorReport.auditColorReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationColorReport.auditReport.auditing.eq(type));
        builder.and(qStationColorReport.questionId.eq(questionId));
        builder.and(qStationColorReport.answerId.eq(String.valueOf(id)));
        List<AuditColorReport> auditColorReportList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);
        for (AuditColorReport auditColorReport : auditColorReportList) {
            idList.add(auditColorReport.getAuditReport().getId());
        }
    }


    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private QuestionRepository questionRepository;


    private List<StationResponse> toStationResponse(List<AuditReport> stationReports) {
        List<StationResponse> stationResponseList = new ArrayList<>();
        for (AuditReport report : stationReports) {
            List<AuditColorReport> colorReports = auditColorReportRepository.selectAnswer(report.getId());
            StationResponse stationResponse = new StationResponse();
            if (colorReports.size() <= 0) {
                continue;
            }
            for (AuditColorReport colorReport : colorReports) {
                if (colorReport.getQuestionId() != null) {
                    if (colorReport.getQuestionId() == 181L) {
                        if (report.getStation() != null) {
                            if (StringUtils.isNotEmpty(report.getStation().getStationNum()) && report.getAuditing().equals(Constants.AUDIT_TRUE)) {
                                stationResponse.setStationNum(report.getStation().getStationNum());
                            } else {
                                stationResponse.setStationNum(colorReport.getAnswerOther());
                            }
                        } else {
                            if (StringUtils.isNotEmpty(colorReport.getAnswerOther())) {
                                stationResponse.setStationNum(colorReport.getAnswerOther());
                            } else {
                                stationResponse.setStationNum("");
                            }
                        }
                    }
                    if (colorReport.getQuestionId() == 173L) {
                        stationResponse.setProvince(colorReport.getAnswerOther());
                    }
                    if (colorReport.getQuestionId() == 174L) {
                        stationResponse.setCity(colorReport.getAnswerOther());
                    }
                    if (colorReport.getQuestionId() == 175L) {
                        stationResponse.setName(colorReport.getAnswerOther());
                    }
                    if (colorReport.getQuestionId() == 8L) {
                        if (StringUtils.isNotEmpty(colorReport.getAnswerId())) {
                            String[] brandIds = colorReport.getAnswerId().split(",");
                            StringBuffer brandBuffer = new StringBuffer("");
                            for (String id : brandIds) {
                                QuestionAnswerOption answer = null;
                                if (StringUtils.isNotEmpty(id)) {
                                    answer = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                                }
                                if (answer != null && answer.getName()!=null) {
                                    if (id.equals("369")) {
                                        brandBuffer.append(colorReport.getAnswerOther() + ",");
                                    } else {
                                        brandBuffer.append(answer.getName() + ",");
                                    }
                                }
                            }
                            stationResponse.setBrand(brandBuffer.toString());
                        }
                    }
                    if (colorReport.getQuestionId() == 7L) {
                        if (StringUtils.isNotEmpty(colorReport.getAnswerId())) {
                            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(colorReport.getAnswerId()));
                            stationResponse.setType(answerOption.getName());
                        } else {
                            stationResponse.setType("");
                        }
                    }
                }
            }
            if (report.getUser() != null) {
                UserProfile userProfile = userProfileRepository.findByUserId(report.getUser().getId());
                if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
                    stationResponse.setUserName(userProfile.getRealName());
                }
            } else {
                stationResponse.setUserName("暂无");
            }

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);
            if (report.getStation() != null) {
                stationResponse.setStationId(report.getStation().getId());
            } else {
                stationResponse.setStationId(null);
            }
            stationResponse.setDateTimeStr(simpleDateFormat.format(report.getUpdateTime()));
            stationResponse.setAuditType(report.getAuditing());
            stationResponse.setReportId(report.getId());
            stationResponseList.add(stationResponse);
        }
        return stationResponseList;
    }


}
